
import asyncio
from agent.streaming_agent import StreamingChatbot, EventType


async def console_app(query: str):
    print("🧠实时响应智能体示例")
    print("=" * 50)

    chatbot = StreamingChatbot(verbose=False, mode="hybrid")

    print(f"❓ Question: {query}")
    print("-" * 50)

    step_count = 0

    async for event in chatbot.chat_stream(query):

        await asyncio.sleep(0)

        if event.type == EventType.THINKING_START:
            step_count += 1
            print(f"🤔 Step {step_count}：开始思考...")

        elif event.type == EventType.THINKING:
            thought = event.data.get("thought", "")
            print(f"💭 想法： {thought[:100]}{'...' if len(thought) > 100 else ''}")

        elif event.type == EventType.ACTION_PLANNED:
            action = event.data.get("action", "")
            action_input = event.data.get("input", "")
            print(f"📋 动作规划：`{action}`，输入参数：`{action_input}`")

        elif event.type == EventType.ACTION_START:
            action = event.data.get("action", "")
            action_input = event.data.get("input", "")
            print(f"🔧 调用工具：`{action}`，输入参数：`{action_input}`")

        elif event.type == EventType.ACTION_RESULT:
            result = event.data.get("result", {})
            if result.get("success"):
                print(f"✅ 工具调用成功 !")
            else:
                print(f"❌ 工具调用失败 ! {result.get('error', '未知错误')}")

        elif event.type == EventType.OBSERVATION:
            observation = event.data.get("observation", "")
            print(f"👁️ 洞察：{observation}")

        elif event.type == EventType.PLAN_CREATED:
            plan = event.data.get("plan", {})
            print(f"📋 计划创建完成.")
            print(f"计划描述：{plan.get('description', '无计划')}")
            steps = plan.get("steps", [])
            if steps:
                print("步骤：")
                for i, step in enumerate(steps, 1):
                    print(f"{i}. {step.get('tool', '未知')}：{step.get('description', '无描述')}")

        elif event.type == EventType.PLAN_STEP_START:
            step_desc = event.data.get("step_description", "")
            tool = event.data.get("tool", "")
            plan_step = event.data.get("plan_step", 0)
            total_steps = event.data.get("total_steps", 0)
            print(f"执行计划 {plan_step}/{total_steps}：调用工具：`{tool}`")
            print(f"_{step_desc}_")

        elif event.type == EventType.PLAN_STEP_COMPLETE:
            print(f"✅ 计划执行完毕！")

        elif event.type == EventType.REFLECTION_START:
            original_response = event.data.get("original_response", "")
            quality_threshold = event.data.get("quality_threshold", 0.7)
            print(f"🔍 开始反思...")
            print(f"当前质量阈值：{quality_threshold:.2f}")
            if original_response:
                print(f"原回答预览：{original_response[:100]}{'...' if len(original_response) > 100 else ''}")

        elif event.type == EventType.REFLECTION_CRITIQUE:
            iteration = event.data.get("iteration", 1)
            critique = event.data.get("critique", {})
            print(f"🤔 反思批评-迭代 {iteration}：")

            quality = critique.get("overall_quality", 0.0)
            confidence = critique.get("confidence", 0.0)
            needs_refinement = critique.get("needs_refinement", False)

            if quality >= 0.8:
                print(f"质量得分：{quality:.2f} (优秀)")
            elif quality >= 0.7:
                print(f"质量得分：{quality:.2f} (良好)")
            elif quality >= 0.5:
                print(f"质量得分：{quality:.2f} (需要改进)")
            else:
                print(f"质量得分：{quality:.2f} (低)")

            print(f"置信度：{confidence:.2f}")
            print(f"需要完善：{'是' if needs_refinement else '否'}")

            issues = critique.get("issues", [])
            if issues:
                print("发现的问题：")
                for i, issue in enumerate(issues, 1):
                    issue_type = issue.get("type", "unknown")
                    severity = issue.get("severity", "unknown")
                    description = issue.get("description", "No description")
                    suggestion = issue.get("suggestion", "No suggestion")

                    severity_emoji = {
                        "critical": "🔴",
                        "major": "🟠",
                        "minor": "🟡",
                        "suggestion": "🔵"
                    }.get(severity.lower(), "⚪")

                    print(f"{severity_emoji} {issue_type.title()} ({severity}): {description}")
                    print(f"💡 建议：{suggestion}")

            strengths = critique.get("strengths", [])
            if strengths:
                print("改进点：")
                for strength in strengths:
                    print(f"✅ {strength}")

            reasoning = critique.get("reasoning", "")
            if reasoning:
                print(f"**推理过程：** {reasoning}")

        elif event.type == EventType.REFLECTION_REFINEMENT:
            improvements = event.data.get("improvements", [])
            quality_improvement = event.data.get("quality_improvement", 0.0)
            print(f"✨ 优化响应：")

            if quality_improvement > 0:
                print(f"质量改进：+{quality_improvement:.2f}")

            if improvements:
                print("改进点：**")
                for improvement in improvements:
                    print(f"🔧 {improvement}")

        elif event.type == EventType.REFLECTION_COMPLETE:
            final_quality = event.data.get("final_quality_score", 0.0)
            threshold_met = event.data.get("threshold_met", False)
            iterations = event.data.get("reflection_iterations", 0)
            total_improvements = event.data.get("total_improvements", 0)
            print(f"🎉 完成反思")

            if threshold_met:
                print(f"✅ 达到质量阈值！最终得分：{final_quality:.2f}")
            else:
                print(f"⚠️ 未达质量阈值！最终得分：{final_quality:.2f}")

            print(f"反思迭代：{iterations}")
            print(f"改进点：{total_improvements}")

        elif event.type == EventType.COMPLETE:
            response = event.data.get("response", {})
            print(f"🎉 最后结果：")
            print(f"📝 {response.get('output', '无输出')}")
            print(f"📊 总步骤数: {step_count}")
            print(f"⚡ 成功：{response.get('success', False)}")
            break

        elif event.type == EventType.ERROR:
            print(f"❌ 失败：{event.data.get('error', '未知错误')}")
            break


if __name__ == "__main__":
    # query = "361的平方根是多少？再告诉我一些关于这个数的趣事。"
    query = "搜索并总结当今物理学发展概括，然后生成一份清晰的Markdown文本报告，最后调用PPT制作工具将Markdown文本转化为PPT。"
    asyncio.run(console_app(query))

